package com.example.demo.service.Impl;

import com.example.demo.ao.CommentAo;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.service.CommentService;
import com.example.demo.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public int insertComment(CommentAo commentAo) {
        if (commentAo.getParentId() == null){
            commentAo.setParentId(0);
        }
        return commentMapper.insertComment(commentAo);
    }

    @Override
    public List<CommentVo> selectVideoById(CommentAo commentAo) {
        List<CommentVo> commentVos = commentMapper.selectVideoById(commentAo.getVideoId());
        return buildCommentTree(commentVos);
    }

    public List<CommentVo> bulidTree(List<CommentVo> commentVos) {

        // 通过Collectors.groupingBy(CommentVo::getParentId)方法对CommentVo按照Pid进行分组，也就是将pid相同的放在一起
        Map<Integer, List<CommentVo>> parentMap = commentVos.stream().collect(Collectors.groupingBy(CommentVo::getParentId));
        commentVos.forEach(item -> {
            item.setChildren(parentMap.get(item.getId()));
        });

//        Map<Integer, List<CommentVo>> parentMap = commentVos.stream()
//                .collect(Collectors.groupingBy(commentVo -> Optional.ofNullable(commentVo.getParentId()).orElse(-1)));
//
//        commentVos.forEach(item -> {
//            // 获取当前评论的子节点列表
//            List<CommentVo> children = parentMap.getOrDefault(item.getId(), new ArrayList<>());
//            item.setChildren(children);
//        });

        // 过滤出根节点集合,根节点已经包含了孩子节点
        List<CommentVo> newList = commentVos.stream().filter(item -> item.getParentId() == null).collect(Collectors.toList());
        return newList;
    }

    public List<CommentVo> buildCommentTree(List<CommentVo> comments) {
        Map<Integer, CommentVo> commentMap = new HashMap<>();
        //跟节点
        List<CommentVo> rootNodes = new ArrayList<>();
        for (CommentVo commentVo : comments) {
            List<CommentVo> objects = new ArrayList<>();
            commentVo.setChildren(objects);
            commentMap.put(commentVo.getId(), commentVo);
        }

        //构建树
        for (CommentVo commentVo : comments) {
            if (commentVo.getParentId() == null) {
                rootNodes.add(commentVo);
            } else {
                CommentVo parent = commentMap.get(commentVo.getParentId());
                if (parent != null) {
                    parent.getChildren().add(commentVo);
                } else {
                    rootNodes.add(commentVo);
                }
            }
        }
        return rootNodes;
    }

}
